<?php

namespace App\Http\Controllers\Api;

use App\ActivityStatus;
use App\Areas;
use App\Dealer;
use App\Http\Resources\DealersResource;
use App\Http\Resources\MobjMoneyResource;
use App\Http\Resources\MobjResource;
use App\Http\Resources\RankResource;
use App\Http\Resources\UsersResource;
use App\Managers;
use App\OrderPolicy;
use App\User;
use Illuminate\Contracts\Encryption\DecryptException;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Rule;
use Illuminate\Support\Facades\Validator;

class UsersController extends Controller
{

    public function getUsersByRoles(Request $request)
    {
        //该接口已弃用
        $user = new User();
        if ($request->area_id == 0) {
            return $user
                ->where('role_id', $request->role_id - 1)
                ->get()
                ->pluck('company', 'id');
        } else {
            return $user->where('area_id', $request->area_id)
                ->where('role_id', $request->role_id - 1)
                ->get()
                ->pluck('company', 'id');
        }
    }

    public function login(Request $request)
    {
        if ($request->userNum[0] != 'A') {
            if (!ActivityStatus::first()->status) {
                return [
                    'success' => false,
                    'activity_status' => false,
                    'error' => '活动已关闭'
                ];
            }
        }

        if (in_array($request->userNum[0], ['A', 'R', 'M'])) {
            return $this->checkManagers($request->userNum, $request->password);
        } elseif ($request->userNum[0] == 'U') {
            return $this->checkDealers($request->userNum, $request->password);
        } else {
            return ['error' => '非法用户', 'success' => false];
        }
    }

    protected function checkManagers($username, $password)
    {
        $manager = Managers::where('username', $username)->first();
        if (!$manager) {
            return ['error' => '未找到该账户'];
        }

        if ($manager->password != $password) {
            return ['error' => '密码错误'];
        }

        if ($manager->id == 1) {
            $manager->role = '管理员';
        }

        if ($username[0] == 'R') {
            $manager->role = '大区经理';
        }

        if ($username[0] == 'M') {
            $manager->role = '区域经理';
        }
        $manager->type = 'manager';
        $token = encrypt($manager);
        $expiresAt = now()->addDay(1);
        Cache::put($manager->username, $manager->id, $expiresAt);
        return ['success' => true, 'token' => $token, 'activity_status' => true];
    }

    protected function checkDealers($username, $password)
    {
        $dealer = Dealer::where('username', $username)->where('is_fake', 0)->first();
        if (!$dealer) {
            return ['error' => '未找到该账户', 'success' => false];
        }

        if ($dealer->password != $password) {
            return ['error' => '密码错误', 'success' => false];
        }
        $dealer->role = '经销商';
        $dealer->type = 'dealer';
        $token = encrypt($dealer);
        $expiresAt = now()->addDay(1);
        Cache::put($dealer->username, $dealer->id, $expiresAt);
        return ['success' => true, 'token' => $token];
    }

    public function getUserInfo(Request $request)
    {

        return UsersResource::make($request->userinfo);
    }

    public function getDetails(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'type' => [
                Rule::in(["unOrder", "order", "all"])
            ],
            'sortType' => [
                Rule::in(['asc', 'desc', 'none'])
            ],
            'page' => 'required'
        ]);
        if ($validator->fails()) {
            return ['error' => '参数错误'];
        }
        $user = $request->userinfo;
        if ($user->type == 'manager') {
            if ($request->sortType == 'none') {
                $dealers = $this->validManagers($user)
                    ->orderByRaw('CONVERT( market USING gbk ) COLLATE gbk_chinese_ci ASC');
            } else {
                $dealers = $this->validManagers($user);
            }
            if ($request->type) {
                $types = [
                    "unOrder" => 0,
                    "order" => 1,
                    "all" => 2,
                ];
                if ($types[$request->type] != 2) {
                    $dealers = $dealers->where('is_order', $types[$request->type]);
                }
            }

            if ($request->keyword) {
                $dealers = $dealers->where('name', 'like', '%' . $request->keyword . '%')
                    ->orWhere('company', 'like', '%' . $request->keyword . '%');
            }

            $dealers = $dealers->get();
            $list = DealersResource::collection($dealers);
            if ($request->sortType == 'asc') {
                $arr = collect($list)->sortBy('moneySum')->values()->all();
            } elseif ($request->sortType == 'desc') {
                $arr = collect($list)->sortByDesc('moneySum')->values()->all();
            } elseif ($request->sortType == 'none') {
                $arr = $list->all();
            }
            return ['shoperList' => array_slice($arr, ($request->page - 1) * 30, 30)];
        } else {
            return ['error' => '无权访问'];
        }
    }

    protected function validManagers($user)
    {
        if ($user->username[0] == "R") {
            $dealers = Dealer::where('region', $user->region)->where('is_fake', 0)->where('market_level', '!=', '抽奖');
        } elseif ($user->username[0] == "M") {
            $dealers = Dealer::where('market', $user->market)->where('is_fake', 0)->where('market_level', '!=', '抽奖');
        } elseif ($user->id == 1) {
            $dealers = Dealer::where('is_fake', 0)->where('market_level', '!=', '抽奖');
        } else {
            abort(404);
        }
        return $dealers;
    }

    public function detailsCount(Request $request)
    {
        $user = $request->userinfo;
        if ($user->type == 'manager') {
            $dealers = $this->validManagers($user);
            $datas = $dealers->get();
            $money = 0;
            $orders = 0;
            foreach ($datas as $data) {
                $money += $data->getAllMoneyCount();
                $orders += $data->getAllGoodsCount();
            }
            $area = [
                'A' => '',
                'R' => '营销总部',
                'M' => '区域',
            ];
            return [
                'success' => true,
                'countInfo' => $user->market . $area[$user->username[0]].",共" . set_decimal($orders) . "万箱,共" . set_decimal($money) . "万元。"
            ];
        }
    }

    public function logout(Request $request)
    {
        $user = $request->userinfo;
        Cache::forget($user->username);
        return ['success' => true];
    }


    public function submit(Request $request)
    {
        if (!ActivityStatus::first()->status) {
            return [
                'success' => false,
                'error' => '活动已关闭',
                'activity_status' => false,
            ];
        }
        $user = $request->userinfo;
        $dealer = Dealer::where('username', $request->userNum)->first();
        if (!$dealer) {
            return ['error' => '非法用户'];
        }
        if ($user->type == 'manager') {
            if ($user->username[0] == "R") {
                if ($dealer->region != $user->region) {
                    return ['error' => '没有权限'];
                }
            }
            if ($user->username[0] == "M") {
                if ($dealer->market != $user->market) {
                    return ['error' => '没有权限'];
                }
            }
        }

        if ($user->type == 'dealer') {
            if ($user->username != $request->userNum) {
                return ['error' => '没有权限'];
            }
        }

        $goodsOrders = $request->input('goodsOrder');
        $data = [];
        foreach ($goodsOrders as $goodsOrder) {
            $data['goods_' . $goodsOrder['productId']] = $goodsOrder['productSum'];
        }
        $data['is_order'] = 1;
        $dealer->update($data);
        return [
            'success' => true,
            'activity_status' => true,
            'goodsCnt' => $dealer->getAllGoodsCount(),
            'goodsOrder' => $goodsOrders,
            'moneySum' => set_decimal($dealer->getAllMoneyCount()),
        ];
    }

    public function productRank(Request $request)
    {
        $user = $request->userinfo;
        if ($user->type == 'manager') {
            $dealers = $this->validManagers($user)->get();
            $data = [
                'goods_1' => 0,
                'goods_2' => 0,
                'goods_3' => 0,
                'goods_4' => 0,
                'goods_5' => 0,
                'goods_6' => 0,
            ];
            foreach ($dealers as $dealer) {
                $data['goods_1'] += $dealer->goods_1;
                $data['goods_2'] += $dealer->goods_2;
                $data['goods_3'] += $dealer->goods_3;
                $data['goods_4'] += $dealer->goods_4;
                $data['goods_5'] += $dealer->goods_5;
                $data['goods_6'] += $dealer->goods_6;
            }
            $list = [];
            foreach ($GLOBALS['goods'] as $good) {
                $arr = [
                    'productId' => $good->id,
                    'productSum' => set_decimal($data['goods_' . $good->id]),
                    'moneyCnt' => set_decimal($data['goods_' . $good->id] * $good->price),
                    'imageUrl' => $good->pic,
                ];
                array_push($list, $arr);
            }
            $sortList = collect($list)->sortByDesc('moneyCnt')->values()->all();
            return [
                'success' => true,
                'list' => $sortList,
            ];
        } else {
            return ['error' => '无权访问'];
        }
    }


    public function allDetails(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'type' => [
                'required',
                Rule::in([0, 1, 2, 3, 4, 5, 6])
            ],
        ]);
        $datas = Dealer::all();
        $money = 0;
        $orders = 0;
        if ($validator->fails()) {
            return ['error' => '非法参数'];
        }
        if ($request->type == 0) {
            foreach ($datas as $data) {
                $money += $data->getAllMoneyCount();
                $orders += $data->getAllGoodsCount();
            }
        } else {
            foreach ($datas as $data) {
                $money += $data->getOneMoneyCount($request->type);
                $orders += $data->getAttributeValue('goods_' . $request->type);
            }
        }
        return [
            'success' => true,
            'money' => $money,
            'orders' => $orders,
        ];
    }

    public function companyRank(Request $request)
    {
        $user = $request->userinfo;
        if ($user->type == 'manager') {
            $dealers = $this->validManagers($user)->get();
            $list = RankResource::collection($dealers);
            $sortList = collect($list)->sortByDesc('moneyCnt')
                ->take(6)
                ->values()
                ->all();
            return [
                'success' => true,
                'list' => $sortList,
            ];
        } else {
            return ['error' => '无权访问'];
        }
    }

    public function rankData(Request $request)
    {
        $user = $request->userinfo;
        if ($user->type == 'manager') {
            $dealers = $this->validManagers($user)->get();
            $list = [];
            foreach ($GLOBALS['goods'] as $good) {
                $sum = $this->goodsCount($dealers, $good->id);
                $products = [
                    'productId' => $good->id,
                    'imageUrl' => $good->pic,
                    'productSum' => set_decimal($sum['productSum']),
                    'moneySum' => set_decimal($sum['moneySum']),
                    'rank' => $this->goodsRank($dealers, $good->id)
                ];
                array_push($list, $products);
            }
            return [
                'success' => true,
                'list' => $list,
            ];
        } else {
            return ['error' => '无权访问'];
        }
    }

    protected function goodsRank($dealers, $id)
    {
        $list = collect($dealers)->sortByDesc('goods_' . $id)->values()->all();
        $collection = [];
        foreach ($list as $value) {
            $products = [
                'userNum' => $value->username,
                'userName' => $value->company,
                'orderSum' => set_decimal($value->getAttributeValue('goods_' . $id)),
                'moneyCnt' => set_decimal($value->getAttributeValue('goods_' . $id) * $GLOBALS['goods'][$id - 1]->price),
            ];
            array_push($collection, $products);
        }
        $rank = collect($collection)->sortByDesc('moneyCnt')
            ->take(3)
            ->values()
            ->all();
        return $rank;
    }

    protected function goodsCount($dealers, $id)
    {
        $moneySum = 0;
        $productSum = 0;
        foreach ($dealers as $dealer) {
            $moneySum += $dealer->getOneMoneyCount($id);
            $productSum += $dealer->getAttributeValue('goods_' . $id);
        }
        return [
            'moneySum' => $moneySum,
            'productSum' => $productSum
        ];
    }

    public function orderPolicy()
    {
        return ['policyImg' => OrderPolicy::first()->img];
    }

    public function getOrderData(Request $request)
    {
        $user = $request->userinfo;
        if ($user->type != 'manager') {
            return ['error' => '无权访问'];
        }
        $dealers = $this->validManagers($user)->get();
        return $this->getGoodsData($dealers, $user);
    }

    public function getGoodsData($dealers, $user)
    {
        if ($user->username[0] == 'M') {
            $pdCntDataList = MobjResource::collection($dealers);
            $pdCntMoneyList = MobjMoneyResource::collection($dealers);
            $totalObj = $this->totalGoods($dealers)['totalObj'];
            $totalMoneyObj = $this->totalMoney($dealers)['totalObj'];
        } elseif ($user->username[0] == 'R') {
            $market = $this->getMarket($user->region);
            $list = [];
            foreach ($market as $value) {
                $list[$value] = $this->getMarketData($value);
            }
            $totalObj = [
                "pd1" => 0,
                "pd2" => 0,
                "pd3" => 0,
                "pd4" => 0,
                "pd5" => 0,
                "pd6" => 0,
                "all" => 0,
            ];
            $pdCntDataList = [];
            $totalMoneyObj = [
                "pd1" => 0,
                "pd2" => 0,
                "pd3" => 0,
                "pd4" => 0,
                "pd5" => 0,
                "pd6" => 0,
                "all" => 0,
            ];
            $pdCntMoneyList = [];

            foreach ($list as $market => $value) {
                foreach ($value['goods']['totalObj'] as $key => $val) {
                        $totalObj[$key] += $val;
                }
                $arr = $value['goods']['totalObj'];
                $arr['total'] = set_float($value['goods']['totalObj']['all']);
                $arr['area'] = $market;
                array_push($pdCntDataList, $arr);
                foreach ($value['money']['totalObj'] as $key => $val) {
                    $totalMoneyObj[$key] += $val;
                }
                $arr = $value['money']['totalObj'];
                $arr['total'] = set_float($value['money']['totalObj']['all']);
                $arr['area'] = $market;
                array_push($pdCntMoneyList, $arr);
            }

        } elseif ($user->id == 1) {
            $market = $this->getRegion();
            $list = [];
            foreach ($market as $value) {
                $list[$value] = $this->getRegionData($value);
            }
            $totalObj = [
                "pd1" => 0,
                "pd2" => 0,
                "pd3" => 0,
                "pd4" => 0,
                "pd5" => 0,
                "pd6" => 0,
                "all" => 0,
            ];
            $pdCntDataList = [];
            $totalMoneyObj = [
                "pd1" => 0,
                "pd2" => 0,
                "pd3" => 0,
                "pd4" => 0,
                "pd5" => 0,
                "pd6" => 0,
                "all" => 0,
            ];
            $pdCntMoneyList = [];

            foreach ($list as $region => $value) {
                foreach ($value['goods']['totalObj'] as $key => $val) {
                    $totalObj[$key] += $val;
                }
                $arr = $value['goods']['totalObj'];
                $arr['total'] = set_float($value['goods']['totalObj']['all']);
                $arr['area'] = $region;
                array_push($pdCntDataList, $arr);
                foreach ($value['money']['totalObj'] as $key => $val) {
                    $totalMoneyObj[$key] += $val;
                }
                $arr = $value['money']['totalObj'];
                $arr['total'] = set_float($value['money']['totalObj']['all']);
                $arr['area'] = $region;
                array_push($pdCntMoneyList, $arr);
            }
        }
        return [
            'goodsCntData' => [
                'pdObj' => $this->getPdObj(),
                'totalObj' => $totalObj,
                'pdCntDataList' => $pdCntDataList
            ],
            'moneyCntData' => [
                "pdObj" => $this->getPdObj(),
                "totalObj" => $totalMoneyObj,
                "pdCntDataList" =>$pdCntMoneyList
            ]
        ];
    }

    protected function getPdObj()
    {
        $pdObj = [];
        foreach ($GLOBALS['goods'] as $good) {
            $arr = [
                "field" => 'pd' . $good->id,
                "pdName" => $good->name
            ];
            array_push($pdObj, $arr);
        }
        return $pdObj;
    }


    protected function getMarket($area)
    {
        $dealers = Dealer::where('region', $area)->where('is_fake', 0)->get();
        $market = [];
        foreach ($dealers as $dealer) {
            array_push($market, $dealer->market);
        }
        return array_unique($market);
    }

    protected function getRegion()
    {
        $areas = Areas::all();
        $regions = [];
        foreach ($areas as $area) {
            array_push($regions, $area->name);
        }
        return $regions;
    }


    protected function getRegionData($region)
    {
        $dealers = Dealer::where('region', $region)->where('is_fake', 0)->get();
        $goods = $this->totalGoods($dealers);
        $money = $this->totalMoney($dealers);
        return [
            'goods' => $goods,
            'money' => $money
        ];
    }

    protected function getMarketData($market)
    {
        $dealers = Dealer::where('market', $market)->where('is_fake', 0)->get();
        $goods = $this->totalGoods($dealers);
        $money = $this->totalMoney($dealers);
        return [
            'goods' => $goods,
            'money' => $money
        ];
    }

    protected function totalGoods($dealers)
    {
        $data = [
            'goods_1' => 0,
            'goods_2' => 0,
            'goods_3' => 0,
            'goods_4' => 0,
            'goods_5' => 0,
            'goods_6' => 0,
        ];
        foreach ($dealers as $dealer) {
            $data['goods_1'] += $dealer->goods_1;
            $data['goods_2'] += $dealer->goods_2;
            $data['goods_3'] += $dealer->goods_3;
            $data['goods_4'] += $dealer->goods_4;
            $data['goods_5'] += $dealer->goods_5;
            $data['goods_6'] += $dealer->goods_6;
        }
        $list = [];
        $totalObj = [];
        foreach ($GLOBALS['goods'] as $good) {
            $totalObj['pd' . $good->id] = set_decimal($data['goods_' . $good->id]);
        }
        $totalObj['all'] = 0;
        foreach ($totalObj as $value) {
            $totalObj['all'] += $value;
        }
        $totalObj['all'] = set_float($totalObj['all']);
        return [
            'totalObj' => $totalObj,
        ];
    }

    protected function totalMoney($dealers)
    {
        $data = [
            'goods_1' => 0,
            'goods_2' => 0,
            'goods_3' => 0,
            'goods_4' => 0,
            'goods_5' => 0,
            'goods_6' => 0,
        ];
        foreach ($dealers as $dealer) {
            $data['goods_1'] += $dealer->goods_1 * $GLOBALS['goods'][0]->price;
            $data['goods_2'] += $dealer->goods_2 * $GLOBALS['goods'][1]->price;
            $data['goods_3'] += $dealer->goods_3 * $GLOBALS['goods'][2]->price;
            $data['goods_4'] += $dealer->goods_4 * $GLOBALS['goods'][3]->price;
            $data['goods_5'] += $dealer->goods_5 * $GLOBALS['goods'][4]->price;
            $data['goods_6'] += $dealer->goods_6 * $GLOBALS['goods'][5]->price;
        }
        $totalObj = [];
        foreach ($GLOBALS['goods'] as $good) {
            $totalObj['pd' . $good->id] = set_decimal($data['goods_' . $good->id]);
        }
        $totalObj['all'] = 0;
        foreach ($totalObj as $value) {
            $totalObj['all'] += $value;
        }
        $totalObj['all'] = set_float($totalObj['all']);
        return [
            'totalObj' => $totalObj,
        ];
    }
}
